package org.unicorn.android.base

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.fragment.app.Fragment

/**
 *
 * @author     : liujianyou
 * @date : 2022/02/16 18:16
 * @Description:
 */

var lastDisplayString = ""
var lastDisplayTime = 0L

val mainHandler by lazy {
    Handler(Looper.getMainLooper())
}

private fun Context.toastPrivate(msg: String) {
    if (msg == lastDisplayString && System.currentTimeMillis() < lastDisplayTime) return
    lastDisplayString = msg
    lastDisplayTime = System.currentTimeMillis() + 4000
    Toast.makeText(this.applicationContext, msg, Toast.LENGTH_SHORT).show()
}

fun Activity.toast(msg: String) {
    if (!isMain()) {
        runOnUiThread {
            toastPrivate(msg)
        }
        return
    }
    toastPrivate(msg)
}

fun Fragment.toast(msg: String) {
    if (!isMain()) {
        mainHandler.post {
            requireContext().toastPrivate(msg)
        }
        return
    }
    requireContext().toastPrivate(msg)
}

fun Context.toast(msg: String) {
    if (!isMain()) {
        mainHandler.post {
            toastPrivate(msg)
        }
        return
    }
    toastPrivate(msg)
}

fun Any.toast(msg: String) {
    AppConfig.App.toast(msg)
}


/**是否是主线程*/
fun isMain() = Looper.getMainLooper() == Looper.myLooper()